﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Weather : System.Web.UI.Page
{

    const string scriptTemplate = "(new SuggestServer()).bind({\"input\": \"{0}\", \"value\": \"@1@\", \"type\": \"61\",  \"max\": 10, \"width\": 280, \"head\": [\"名称\", \"区号\"], \"body\": [1, 2], \"callback\": null, \"tip\": \"可输入汉字/拼音/缩写/区号\" });";
    protected void Page_Load(object sender, EventArgs e)
    {
        HttpContext.Current.Session["LastUrl"] = "./Weather.aspx";
        this.DropDownList3.SelectedIndex = 9;
        if (!this.IsPostBack)
        {
            this.Button4.Enabled = false;
        }
        else
        {
            this.Button4.Enabled = true;
        }
        if (User.Identity.IsAuthenticated)
        {
            global::User user = UserManager.GetInstance().FindUser(User.Identity.Name);
            {
                if (user.IsValidate)
                {
                    this.ListView.Visible = true;
                    //foreach (ListViewItem item in this.ListView.Items)
                    //{
                    //    string id = item.FindControl("CityTextBox").ClientID;
                    //    this.ClientScript.RegisterStartupScript(this.GetType(), 
                    //        "clientScript", 
                    //        string.Format(scriptTemplate, id), true);
                    //}
                    return;
                }
            }
        }
        this.ListView.Visible = false;
    }

    // Done, when this button click, add an item the viewstate objects.
    protected void Button3_Click(object sender, EventArgs e)
    {
        try
        {
            Utility.CheckLoginAndRedirect();

            global::User user = UserManager.GetInstance().FindUser(User.Identity.Name);
            if (user.Money - user.ConsumedMoneyEveryMonth < WeatherService.ItemPrice)
            {
                this.Label2.ForeColor = Color.Red;
                this.Label2.Text = ConstStrings.NotEnoughMoney;
            }
            WeatherService service = ViewState[ViewStateConst] as WeatherService;
            if (service == null)
            {
                service = new WeatherService();
                ViewState[ViewStateConst] = service;
            }

            service.Entities.Add(new WeatherSerivceEntity()
            {
                City = this.CityNameTextBox.Text,
                Time = this.DropDownList3.SelectedValue,
                ShouldSendZS = this.CheckBox1.Checked ? "Yes" : "No"
            });
            this.ListView.DataBind();
            foreach (ListViewDataItem item in this.ListView.Items)
            {
                this.ListView.UpdateItem(item.DataItemIndex, false);
            }
        }
        catch
        {

        }
    }

    protected void ListView1_ItemCommand(object sender, ListViewCommandEventArgs e)
    {
        foreach (ListViewDataItem item in this.ListView.Items)
        {
            this.ListView.UpdateItem(item.DataItemIndex, false);
        }
    }

    protected void ListView1_ItemUpdating(object sender, ListViewUpdateEventArgs e)
    {
        // These could also be defined in the aspx and just referenced here with like e.NewValues["ListIndex"]..  but if
        //  we have to do them manually for the Delete anyway, might as well do them all manually and keep them together 
        //   in the code-behind.
        this.objService.UpdateParameters.Clear();
        objService.UpdateParameters.Add(new Parameter("ListIndex", TypeCode.Int16, e.ItemIndex.ToString()));
        objService.UpdateParameters.Add(new Parameter("City", TypeCode.String,
            ((TextBox)this.ListView.Items[e.ItemIndex].FindControl("CityTextBox")).Text));
        objService.UpdateParameters.Add(new Parameter("Time", TypeCode.String,
            ((DropDownList)this.ListView.Items[e.ItemIndex].FindControl("TimeDropDownList")).SelectedValue));
        objService.UpdateParameters.Add(new Parameter("ShouldSendZS", TypeCode.String,
            ((DropDownList)this.ListView.Items[e.ItemIndex].FindControl("YesNoDropDownList")).SelectedValue));
    }

    protected void ListView1_ItemDeleting(object sender, ListViewDeleteEventArgs e)
    {
        // The ListIndex parameter could have been defined in the aspx - DeleteParameters collection of the ObjectDataSource,
        //  but then we'd have to reference it here by objOfficer.DeleteParameters["ListIndex"].DefaultValue - and unfortunately
        //   DefaultValue only accepts strings (regardless of Parameter type)
        objService.DeleteParameters.Clear();
        objService.DeleteParameters.Add(new Parameter("ListIndex", TypeCode.Int16, e.ItemIndex.ToString()));
    }

    private string ViewStateConst = "WeatherService";

    protected void objService_ObjectCreating(object sender, ObjectDataSourceEventArgs e)
    {
        // pass in ViewState for accessing from the class
        if (ViewState[ViewStateConst] != null)
        {
            e.ObjectInstance = ViewState[ViewStateConst] as WeatherService;
        }
        else
        {
            global::User user = UserManager.GetInstance().FindUser(User.Identity.Name);
            ServiceManager serviceManager = ServiceManager.LoadFromFile(user.ServiceFileName);
            if (serviceManager != null && serviceManager.WeatherService != null)
            {
                e.ObjectInstance = serviceManager.WeatherService;
            }
            else
            {
                e.ObjectInstance = new WeatherService();
            }
            ViewState[ViewStateConst] = e.ObjectInstance;
        }
    }

    private delegate void DoStuff(string s1, string s2);

    private void SendOut(string s1, string s2)
    {
        SendMail.Send(MailAccounts.GetInstance().Weather, "Update:" + s1,
           s2, false, ConstStrings.RootMail);
    }


    protected void Button4_Click(object sender, EventArgs e)
    {
        Utility.CheckLoginAndRedirect();
        global::User user = UserManager.GetInstance().FindUser(User.Identity.Name);
        ServiceManager serviceManager = ServiceManager.LoadFromFile(user.ServiceFileName);
        this.ListView1_ItemCommand(null, null);


        int original = 0;
        if (serviceManager.WeatherService != null)
        {
            original = serviceManager.WeatherService.Entities.Count * WeatherService.ItemPrice;
        }
        serviceManager.WeatherService = ViewState[ViewStateConst] as WeatherService;
        user.ConsumedMoneyEveryMonth = user.ConsumedMoneyEveryMonth - original +
                                            serviceManager.WeatherService.Entities.Count * WeatherService.ItemPrice;

        DataManager dataMan = new DataManager(user.ServiceFileName, typeof(ServiceManager));
        dataMan.SaveData(serviceManager);
        this.Button4.Enabled = false;

        DoStuff action = new DoStuff(SendOut);
        action.BeginInvoke(user.PhoneNumber, serviceManager.WeatherService.SerializeToString(), null, null);
    }

}